/**
 * @file thread_pool_comprehensive_test.cpp
 * @brief 线程池模块全面测试
 * @author AI Assistant
 * @date 2025/7/8
 * 
 * 测试覆盖：
 * - 基本功能测试
 * - 配置测试
 * - 性能测试
 * - 并发安全测试
 * - 动态调整测试
 * - 监控功能测试
 * - 异常处理测试
 * - 边界条件测试
 */

#include <iostream>
#include <chrono>
#include <atomic>
#include <vector>
#include <future>
#include <random>
#include <thread>
#include <cassert>
#include <algorithm>
#include <numeric>

#include "common/thread_pool/thread_pool.h"
#include "common/config/config_manager.h"
#include "common/logger/logger.h"

using namespace common::thread_pool;
using namespace common::config;
using namespace common::logger;

// 测试统计类
class TestStats {
private:
    std::atomic<int> passed_{0};
    std::atomic<int> failed_{0};
    std::vector<std::string> failures_;
    std::mutex failures_mutex_;

public:
    void recordTest(bool success, const std::string& test_name) {
        if (success) {
            passed_++;
            std::cout << "✓ " << test_name << std::endl;
        } else {
            failed_++;
            std::cout << "✗ " << test_name << " - FAILED" << std::endl;
            std::lock_guard<std::mutex> lock(failures_mutex_);
            failures_.push_back(test_name);
        }
    }

    void printSummary() {
        int total = passed_ + failed_;
        std::cout << "\n" << std::string(60, '=') << std::endl;
        std::cout << "测试总结: " << passed_ << "/" << total << " 通过";
        if (failed_ > 0) {
            std::cout << " (" << failed_ << " 失败)";
        }
        std::cout << std::endl;
        
        if (!failures_.empty()) {
            std::cout << "\n失败的测试:" << std::endl;
            for (const auto& failure : failures_) {
                std::cout << "  - " << failure << std::endl;
            }
        }
        std::cout << std::string(60, '=') << std::endl;
    }

    bool allPassed() const { return failed_ == 0; }
};

TestStats g_testStats;

// 测试辅助函数
class TestHelper {
public:
    // 创建简单任务
    static std::function<int()> createSimpleTask(int value) {
        return [value]() -> int {
            std::this_thread::sleep_for(std::chrono::milliseconds(10));
            return value * 2;
        };
    }

    // 创建长时间运行任务
    static std::function<void()> createLongTask(int duration_ms) {
        return [duration_ms]() {
            std::this_thread::sleep_for(std::chrono::milliseconds(duration_ms));
        };
    }

    // 创建抛异常的任务
    static std::function<void()> createExceptionTask(const std::string& message) {
        return [message]() {
            throw std::runtime_error(message);
        };
    }

    // 创建CPU密集型任务
    static std::function<long()> createCpuIntensiveTask(int iterations) {
        return [iterations]() -> long {
            long sum = 0;
            for (int i = 0; i < iterations; ++i) {
                sum += i * i;
            }
            return sum;
        };
    }

    // 等待指定时间
    static void waitMs(int ms) {
        std::this_thread::sleep_for(std::chrono::milliseconds(ms));
    }

    // 测量执行时间
    template<typename Func>
    static auto measureTime(Func&& func) {
        auto start = std::chrono::high_resolution_clock::now();
        func();
        auto end = std::chrono::high_resolution_clock::now();
        return std::chrono::duration_cast<std::chrono::milliseconds>(end - start);
    }
};

// 前置声明
void testBasicFunctionality();
void testConfigurationValidation();
void testTaskSubmissionAndExecution();
void testConcurrentAccess();
void testDynamicPoolSizing();
void testMonitoringFeatures();
void testExceptionHandling();
void testPerformanceBenchmarks();
void testBoundaryConditions();
void testConfigHotReload();
void testShutdownBehavior();
void testMemoryManagement();

int main() {
    std::cout << "线程池模块全面测试" << std::endl;
    std::cout << "==================" << std::endl;
    
    try {
        // 初始化Logger避免循环依赖
        if (!Logger::getInstance().isInitializedFromConfig()) {
            Logger::getInstance().initializeFromConfig();
        }

        // 执行所有测试
        testBasicFunctionality();
        testConfigurationValidation();
        testTaskSubmissionAndExecution();
        testConcurrentAccess();
        testDynamicPoolSizing();
        testMonitoringFeatures();
        testExceptionHandling();
        testPerformanceBenchmarks();
        testBoundaryConditions();
        testConfigHotReload();
        testShutdownBehavior();
        testMemoryManagement();

        // 打印测试总结
        g_testStats.printSummary();
        
        return g_testStats.allPassed() ? 0 : 1;
        
    } catch (const std::exception& e) {
        std::cerr << "测试过程中发生异常: " << e.what() << std::endl;
        return 1;
    }
}

void testBasicFunctionality() {
    std::cout << "\n=== 测试基本功能 ===" << std::endl;
    
    try {
        // 测试默认构造函数
        {
            ThreadPool pool(4);
            g_testStats.recordTest(pool.getTotalThreadCount() == 4, "默认构造函数创建指定数量线程");
            g_testStats.recordTest(pool.getActiveThreadCount() == 0, "初始活跃线程数为0");
            g_testStats.recordTest(pool.getQueueSize() == 0, "初始队列大小为0");
            g_testStats.recordTest(!pool.isShutdown(), "初始状态未关闭");
        }

        // 测试硬件并发构造函数
        {
            ThreadPool pool(0);  // 应该使用硬件并发数
            size_t expected = std::thread::hardware_concurrency();
            if (expected == 0) expected = 8;
            g_testStats.recordTest(pool.getTotalThreadCount() == expected, "硬件并发数构造函数");
        }

        // 测试配置构造函数
        {
            ThreadPool::Config config;
            config.core_pool_size = 6;
            config.maximum_pool_size = 12;
            config.enable_monitoring = false;
            
            ThreadPool pool(config);
            g_testStats.recordTest(pool.getTotalThreadCount() == 6, "配置构造函数创建正确数量线程");
        }

    } catch (const std::exception& e) {
        g_testStats.recordTest(false, "基本功能测试异常: " + std::string(e.what()));
    }
}

void testConfigurationValidation() {
    std::cout << "\n=== 测试配置验证 ===" << std::endl;

    try {
        // 测试有效配置
        {
            ThreadPool::Config config;
            config.core_pool_size = 4;
            config.maximum_pool_size = 8;
            config.queue_capacity = 100;
            config.keep_alive_time_ms = 60000;
            config.rejection_policy = "abort";

            bool valid = true;
            try {
                config.validate();
            } catch (...) {
                valid = false;
            }
            g_testStats.recordTest(valid, "有效配置验证通过");
        }

        // 测试无效配置 - 核心线程数 <= 0
        {
            ThreadPool::Config config;
            config.core_pool_size = 0;

            bool caught_exception = false;
            try {
                config.validate();
            } catch (const std::runtime_error&) {
                caught_exception = true;
            }
            g_testStats.recordTest(caught_exception, "核心线程数<=0时抛出异常");
        }

        // 测试无效配置 - 最大线程数 < 核心线程数
        {
            ThreadPool::Config config;
            config.core_pool_size = 8;
            config.maximum_pool_size = 4;

            bool caught_exception = false;
            try {
                config.validate();
            } catch (const std::runtime_error&) {
                caught_exception = true;
            }
            g_testStats.recordTest(caught_exception, "最大线程数<核心线程数时抛出异常");
        }

        // 测试无效配置 - 队列容量 <= 0
        {
            ThreadPool::Config config;
            config.queue_capacity = 0;

            bool caught_exception = false;
            try {
                config.validate();
            } catch (const std::runtime_error&) {
                caught_exception = true;
            }
            g_testStats.recordTest(caught_exception, "队列容量<=0时抛出异常");
        }

        // 测试无效配置 - 无效拒绝策略
        {
            ThreadPool::Config config;
            config.rejection_policy = "invalid_policy";

            bool caught_exception = false;
            try {
                config.validate();
            } catch (const std::runtime_error&) {
                caught_exception = true;
            }
            g_testStats.recordTest(caught_exception, "无效拒绝策略时抛出异常");
        }

        // 测试有效拒绝策略
        std::vector<std::string> valid_policies = {"abort", "discard", "caller_runs"};
        for (const auto& policy : valid_policies) {
            ThreadPool::Config config;
            config.rejection_policy = policy;

            bool valid = true;
            try {
                config.validate();
            } catch (...) {
                valid = false;
            }
            g_testStats.recordTest(valid, "拒绝策略 '" + policy + "' 验证通过");
        }

    } catch (const std::exception& e) {
        g_testStats.recordTest(false, "配置验证测试异常: " + std::string(e.what()));
    }
}

void testTaskSubmissionAndExecution() {
    std::cout << "\n=== 测试任务提交和执行 ===" << std::endl;

    try {
        ThreadPool pool(4);

        // 测试简单任务提交
        {
            auto future = pool.submit(TestHelper::createSimpleTask(5));
            int result = future.get();
            g_testStats.recordTest(result == 10, "简单任务执行结果正确");
        }

        // 测试多个任务并发执行
        {
            std::vector<std::future<int>> futures;
            const int task_count = 20;

            for (int i = 0; i < task_count; ++i) {
                futures.push_back(pool.submit(TestHelper::createSimpleTask(i)));
            }

            bool all_correct = true;
            for (int i = 0; i < task_count; ++i) {
                int result = futures[i].get();
                if (result != i * 2) {
                    all_correct = false;
                    break;
                }
            }
            g_testStats.recordTest(all_correct, "多任务并发执行结果正确");
        }

        // 测试不同类型的任务
        {
            // 无返回值任务
            std::atomic<bool> executed{false};
            auto future1 = pool.submit([&executed]() {
                executed = true;
            });
            future1.get();
            g_testStats.recordTest(executed.load(), "无返回值任务执行成功");

            // 带参数任务
            auto future2 = pool.submit([](int a, int b) -> int {
                return a + b;
            }, 3, 7);
            int sum = future2.get();
            g_testStats.recordTest(sum == 10, "带参数任务执行结果正确");

            // 返回字符串任务
            auto future3 = pool.submit([]() -> std::string {
                return "Hello ThreadPool";
            });
            std::string result = future3.get();
            g_testStats.recordTest(result == "Hello ThreadPool", "字符串返回任务执行正确");
        }

        // 测试任务队列统计
        {
            // 提交长时间运行的任务填满线程
            std::vector<std::future<void>> long_futures;
            for (int i = 0; i < 4; ++i) {
                long_futures.push_back(pool.submit(TestHelper::createLongTask(200)));
            }

            // 提交更多任务到队列
            std::vector<std::future<void>> queue_futures;
            for (int i = 0; i < 10; ++i) {
                queue_futures.push_back(pool.submit(TestHelper::createLongTask(50)));
            }

            TestHelper::waitMs(50);  // 等待任务开始执行

            size_t active_count = pool.getActiveThreadCount();
            size_t queue_size = pool.getQueueSize();

            g_testStats.recordTest(active_count > 0, "活跃线程数统计正确");
            g_testStats.recordTest(queue_size > 0, "队列大小统计正确");

            // 等待所有任务完成
            for (auto& f : long_futures) f.get();
            for (auto& f : queue_futures) f.get();
        }

    } catch (const std::exception& e) {
        g_testStats.recordTest(false, "任务提交执行测试异常: " + std::string(e.what()));
    }
}

void testConcurrentAccess() {
    std::cout << "\n=== 测试并发访问安全性 ===" << std::endl;

    try {
        ThreadPool pool(8);
        const int thread_count = 10;
        const int tasks_per_thread = 50;

        // 测试多线程同时提交任务
        {
            std::vector<std::thread> submitter_threads;
            std::vector<std::vector<std::future<int>>> all_futures(thread_count);

            for (int t = 0; t < thread_count; ++t) {
                submitter_threads.emplace_back([&, t]() {
                    for (int i = 0; i < tasks_per_thread; ++i) {
                        all_futures[t].push_back(
                            pool.submit(TestHelper::createSimpleTask(t * tasks_per_thread + i))
                        );
                    }
                });
            }

            // 等待所有提交线程完成
            for (auto& thread : submitter_threads) {
                thread.join();
            }

            // 验证所有任务结果
            bool all_correct = true;
            for (int t = 0; t < thread_count; ++t) {
                for (int i = 0; i < tasks_per_thread; ++i) {
                    int expected = (t * tasks_per_thread + i) * 2;
                    int actual = all_futures[t][i].get();
                    if (actual != expected) {
                        all_correct = false;
                        break;
                    }
                }
                if (!all_correct) break;
            }

            g_testStats.recordTest(all_correct, "多线程并发提交任务结果正确");
        }

        // 测试并发访问统计信息
        {
            std::atomic<bool> stop_flag{false};
            std::vector<std::thread> stat_threads;
            std::atomic<int> stat_errors{0};

            // 启动统计访问线程
            for (int i = 0; i < 5; ++i) {
                stat_threads.emplace_back([&]() {
                    while (!stop_flag.load()) {
                        try {
                            volatile size_t queue_size = pool.getQueueSize();
                            volatile size_t active_count = pool.getActiveThreadCount();
                            volatile size_t total_count = pool.getTotalThreadCount();
                            (void)queue_size; (void)active_count; (void)total_count;
                        } catch (...) {
                            stat_errors++;
                        }
                        std::this_thread::sleep_for(std::chrono::milliseconds(1));
                    }
                });
            }

            // 同时提交任务
            std::vector<std::future<void>> concurrent_futures;
            for (int i = 0; i < 100; ++i) {
                concurrent_futures.push_back(pool.submit(TestHelper::createLongTask(10)));
            }

            TestHelper::waitMs(100);
            stop_flag = true;

            for (auto& thread : stat_threads) {
                thread.join();
            }

            for (auto& future : concurrent_futures) {
                future.get();
            }

            g_testStats.recordTest(stat_errors.load() == 0, "并发访问统计信息无错误");
        }

    } catch (const std::exception& e) {
        g_testStats.recordTest(false, "并发访问测试异常: " + std::string(e.what()));
    }
}

void testDynamicPoolSizing() {
    std::cout << "\n=== 测试动态线程池调整 ===" << std::endl;

    try {
        ThreadPool::Config config;
        config.core_pool_size = 4;
        config.maximum_pool_size = 12;
        config.enable_monitoring = false;

        ThreadPool pool(config);

        // 测试核心线程数调整 - 扩容
        {
            size_t initial_count = pool.getTotalThreadCount();
            pool.adjustCorePoolSize(8);
            TestHelper::waitMs(100);  // 等待线程创建

            size_t new_count = pool.getTotalThreadCount();
            g_testStats.recordTest(new_count > initial_count, "核心线程池扩容成功");
        }

        // 测试核心线程数调整 - 缩容
        {
            size_t before_count = pool.getTotalThreadCount();
            pool.adjustCorePoolSize(6);
            TestHelper::waitMs(100);  // 等待调整生效

            size_t after_count = pool.getTotalThreadCount();
            // 注意：缩容可能不会立即减少线程数，而是标记线程在空闲时退出
            g_testStats.recordTest(after_count <= before_count, "核心线程池缩容调用成功");
        }

        // 测试最大线程数调整
        {
            pool.adjustMaximumPoolSize(16);
            g_testStats.recordTest(true, "最大线程池大小调整成功");
        }

        // 测试无效调整
        {
            bool caught_warning = true;  // 应该记录警告但不抛异常
            try {
                pool.adjustCorePoolSize(-1);  // 无效值
                pool.adjustMaximumPoolSize(2);  // 小于核心线程数
            } catch (...) {
                caught_warning = false;
            }
            g_testStats.recordTest(caught_warning, "无效调整参数处理正确");
        }

    } catch (const std::exception& e) {
        g_testStats.recordTest(false, "动态调整测试异常: " + std::string(e.what()));
    }
}

void testMonitoringFeatures() {
    std::cout << "\n=== 测试监控功能 ===" << std::endl;

    try {
        ThreadPool::Config config;
        config.core_pool_size = 4;
        config.enable_monitoring = true;
        config.monitoring_interval_ms = 100;

        ThreadPool pool(config);

        // 测试监控启动
        {
            TestHelper::waitMs(200);  // 等待监控线程启动
            g_testStats.recordTest(true, "监控功能启动成功");
        }

        // 测试状态报告
        {
            // 提交一些任务以产生状态变化
            std::vector<std::future<void>> futures;
            for (int i = 0; i < 10; ++i) {
                futures.push_back(pool.submit(TestHelper::createLongTask(50)));
            }

            TestHelper::waitMs(300);  // 等待监控报告

            for (auto& future : futures) {
                future.get();
            }

            g_testStats.recordTest(true, "监控状态报告功能正常");
        }

        // 测试监控停止
        {
            pool.stopMonitoring();
            TestHelper::waitMs(200);
            g_testStats.recordTest(true, "监控功能停止成功");
        }

    } catch (const std::exception& e) {
        g_testStats.recordTest(false, "监控功能测试异常: " + std::string(e.what()));
    }
}

void testExceptionHandling() {
    std::cout << "\n=== 测试异常处理 ===" << std::endl;

    try {
        ThreadPool pool(4);

        // 测试任务异常不影响线程池
        {
            std::vector<std::future<void>> futures;

            // 提交会抛异常的任务
            for (int i = 0; i < 5; ++i) {
                futures.push_back(pool.submit(
                    TestHelper::createExceptionTask("Test exception " + std::to_string(i))
                ));
            }

            // 提交正常任务
            auto normal_future = pool.submit(TestHelper::createSimpleTask(42));

            // 异常任务应该被捕获，不影响线程池运行
            for (auto& future : futures) {
                try {
                    future.get();
                } catch (const std::exception&) {
                    // 预期的异常
                }
            }

            // 正常任务应该能正常执行
            int result = normal_future.get();
            g_testStats.recordTest(result == 84, "任务异常不影响线程池正常运行");
        }

        // 测试关闭后提交任务
        {
            ThreadPool temp_pool(2);
            temp_pool.shutdown();

            bool caught_exception = false;
            try {
                auto future = temp_pool.submit(TestHelper::createSimpleTask(1));
                future.get();
            } catch (const std::runtime_error&) {
                caught_exception = true;
            }

            g_testStats.recordTest(caught_exception, "关闭后提交任务抛出异常");
        }

        // 测试线程池状态一致性
        {
            g_testStats.recordTest(!pool.isShutdown(), "线程池状态一致性检查");
            g_testStats.recordTest(pool.getTotalThreadCount() > 0, "线程数量一致性检查");
        }

    } catch (const std::exception& e) {
        g_testStats.recordTest(false, "异常处理测试异常: " + std::string(e.what()));
    }
}

void testPerformanceBenchmarks() {
    std::cout << "\n=== 测试性能基准 ===" << std::endl;

    try {
        ThreadPool pool(8);

        // 测试任务提交性能
        {
            const int task_count = 10000;
            std::vector<std::future<int>> futures;
            futures.reserve(task_count);

            auto submit_time = TestHelper::measureTime([&]() {
                for (int i = 0; i < task_count; ++i) {
                    futures.push_back(pool.submit([i]() -> int { return i; }));
                }
            });

            // 等待所有任务完成
            for (auto& future : futures) {
                future.get();
            }

            double submit_rate = static_cast<double>(task_count) / submit_time.count() * 1000;
            std::cout << "  任务提交速率: " << static_cast<int>(submit_rate) << " 任务/秒" << std::endl;
            g_testStats.recordTest(submit_rate > 1000, "任务提交性能满足要求");
        }

        // 测试CPU密集型任务性能
        {
            const int cpu_task_count = 100;
            const int iterations = 100000;
            std::vector<std::future<long>> cpu_futures;

            auto cpu_time = TestHelper::measureTime([&]() {
                for (int i = 0; i < cpu_task_count; ++i) {
                    cpu_futures.push_back(pool.submit(TestHelper::createCpuIntensiveTask(iterations)));
                }

                for (auto& future : cpu_futures) {
                    future.get();
                }
            });

            std::cout << "  CPU密集型任务执行时间: " << cpu_time.count() << " ms" << std::endl;
            g_testStats.recordTest(cpu_time.count() < 10000, "CPU密集型任务性能合理");
        }

        // 测试内存使用效率
        {
            const int memory_task_count = 1000;
            std::vector<std::future<std::vector<int>>> memory_futures;

            for (int i = 0; i < memory_task_count; ++i) {
                memory_futures.push_back(pool.submit([i]() -> std::vector<int> {
                    std::vector<int> data(1000, i);
                    return data;
                }));
            }

            bool memory_test_passed = true;
            for (auto& future : memory_futures) {
                try {
                    auto result = future.get();
                    if (result.size() != 1000) {
                        memory_test_passed = false;
                        break;
                    }
                } catch (...) {
                    memory_test_passed = false;
                    break;
                }
            }

            g_testStats.recordTest(memory_test_passed, "内存使用效率测试通过");
        }

    } catch (const std::exception& e) {
        g_testStats.recordTest(false, "性能基准测试异常: " + std::string(e.what()));
    }
}

void testBoundaryConditions() {
    std::cout << "\n=== 测试边界条件 ===" << std::endl;

    try {
        // 测试最小线程池
        {
            ThreadPool small_pool(1);
            auto future = small_pool.submit(TestHelper::createSimpleTask(5));
            int result = future.get();
            g_testStats.recordTest(result == 10, "单线程线程池正常工作");
        }

        // 测试大量线程
        {
            const size_t large_thread_count = 50;
            ThreadPool large_pool(large_thread_count);
            g_testStats.recordTest(large_pool.getTotalThreadCount() == large_thread_count, "大量线程创建成功");

            // 提交大量任务
            std::vector<std::future<int>> futures;
            for (int i = 0; i < 100; ++i) {
                futures.push_back(large_pool.submit(TestHelper::createSimpleTask(i)));
            }

            bool all_completed = true;
            for (int i = 0; i < 100; ++i) {
                try {
                    int result = futures[i].get();
                    if (result != i * 2) {
                        all_completed = false;
                        break;
                    }
                } catch (...) {
                    all_completed = false;
                    break;
                }
            }
            g_testStats.recordTest(all_completed, "大量线程处理大量任务成功");
        }

        // 测试空任务
        {
            ThreadPool pool(4);
            auto future = pool.submit([]() {});
            future.get();
            g_testStats.recordTest(true, "空任务执行成功");
        }

        // 测试立即返回的任务
        {
            ThreadPool pool(4);
            auto future = pool.submit([]() -> int { return 42; });
            int result = future.get();
            g_testStats.recordTest(result == 42, "立即返回任务执行正确");
        }

    } catch (const std::exception& e) {
        g_testStats.recordTest(false, "边界条件测试异常: " + std::string(e.what()));
    }
}

void testConfigHotReload() {
    std::cout << "\n=== 测试配置热重载 ===" << std::endl;

    try {
        ThreadPool::Config config;
        config.core_pool_size = 4;
        config.maximum_pool_size = 8;
        config.enable_monitoring = false;

        ThreadPool pool(config);

        // 测试启用热重载
        {
            pool.enableConfigHotReload();
            g_testStats.recordTest(true, "配置热重载启用成功");
        }

        // 测试配置变更监听
        {
            auto& config_manager = ConfigManager::getInstance();

            // 设置初始配置
            config_manager.set("thread_pool.core_pool_size", 4);
            config_manager.set("thread_pool.maximum_pool_size", 8);

            TestHelper::waitMs(100);

            // 模拟配置变更
            config_manager.set("thread_pool.core_pool_size", 6);
            TestHelper::waitMs(200);  // 等待配置变更处理

            g_testStats.recordTest(true, "配置变更监听功能正常");
        }

    } catch (const std::exception& e) {
        g_testStats.recordTest(false, "配置热重载测试异常: " + std::string(e.what()));
    }
}

void testShutdownBehavior() {
    std::cout << "\n=== 测试关闭行为 ===" << std::endl;

    try {
        // 测试优雅关闭
        {
            ThreadPool pool(4);

            // 提交一些任务
            std::vector<std::future<int>> futures;
            for (int i = 0; i < 10; ++i) {
                futures.push_back(pool.submit(TestHelper::createSimpleTask(i)));
            }

            // 关闭线程池
            pool.shutdown();
            g_testStats.recordTest(pool.isShutdown(), "线程池关闭状态正确");

            // 等待已提交的任务完成
            bool all_completed = true;
            for (int i = 0; i < 10; ++i) {
                try {
                    int result = futures[i].get();
                    if (result != i * 2) {
                        all_completed = false;
                        break;
                    }
                } catch (...) {
                    all_completed = false;
                    break;
                }
            }
            g_testStats.recordTest(all_completed, "关闭前提交的任务正常完成");
        }

        // 测试析构函数关闭
        {
            std::atomic<bool> task_completed{false};
            {
                ThreadPool temp_pool(2);
                temp_pool.submit([&task_completed]() {
                    TestHelper::waitMs(100);
                    task_completed = true;
                });
                // temp_pool析构时应该等待任务完成
            }
            g_testStats.recordTest(task_completed.load(), "析构函数等待任务完成");
        }

    } catch (const std::exception& e) {
        g_testStats.recordTest(false, "关闭行为测试异常: " + std::string(e.what()));
    }
}

void testMemoryManagement() {
    std::cout << "\n=== 测试内存管理 ===" << std::endl;

    try {
        // 测试大量任务的内存管理
        {
            ThreadPool pool(4);
            const int large_task_count = 10000;

            // 提交大量小任务
            for (int i = 0; i < large_task_count; ++i) {
                pool.submit([i]() {
                    volatile int x = i * i;  // 简单计算
                    (void)x;
                });
            }

            TestHelper::waitMs(1000);  // 等待任务完成

            // 检查队列是否清空
            size_t final_queue_size = pool.getQueueSize();
            g_testStats.recordTest(final_queue_size == 0, "大量任务完成后队列清空");
        }

        // 测试重复创建和销毁
        {
            for (int i = 0; i < 10; ++i) {
                ThreadPool temp_pool(4);
                auto future = temp_pool.submit(TestHelper::createSimpleTask(i));
                int result = future.get();
                if (result != i * 2) {
                    g_testStats.recordTest(false, "重复创建销毁测试失败");
                    return;
                }
            }
            g_testStats.recordTest(true, "重复创建销毁线程池正常");
        }

        // 测试长时间运行的内存稳定性
        {
            ThreadPool pool(4);
            std::atomic<int> completed_tasks{0};

            // 持续提交任务
            for (int i = 0; i < 1000; ++i) {
                pool.submit([&completed_tasks]() {
                    TestHelper::waitMs(1);
                    completed_tasks++;
                });
            }

            // 等待所有任务完成
            while (completed_tasks.load() < 1000) {
                TestHelper::waitMs(10);
            }

            g_testStats.recordTest(completed_tasks.load() == 1000, "长时间运行内存稳定");
        }

    } catch (const std::exception& e) {
        g_testStats.recordTest(false, "内存管理测试异常: " + std::string(e.what()));
    }
}
